package com.cntaiping.royal.bass.system.service.serviceImpl;

import com.cntaiping.royal.bass.system.entity.SysResource;
import com.cntaiping.royal.bass.system.mapper.BaseMapper;
import com.cntaiping.royal.bass.system.mapper.SysResourceMapper;
import com.cntaiping.royal.bass.system.service.SysResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by FCHEN on 2016/12/12.
 */
@Service
public class SysResourceServiceImpl extends BaseServiceImpl<SysResource> implements SysResourceService {

    @Autowired
    private SysResourceMapper sysResourceMapper;

    @Override
    public BaseMapper<SysResource> getMapper() {
        return sysResourceMapper;
    }

    @Override
    public List<SysResource> findByUserId(SysResource sysResource){
        return sysResourceMapper.findByUserId(sysResource);
    }

    @Override
    public void saveReSource(SysResource sysResource) {
        // 获取父节点实体
        sysResource.setParent(this.queryById(sysResource.getParent().getId()));

        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = sysResource.getParentIds();

        // 设置新的父节点串
        sysResource.setParentIds(sysResource.getParent().getParentIds()+sysResource.getParent().getId()+",");

        // 保存或更新实体
        if (sysResource.getId() == null ){
            sysResourceMapper.add(sysResource);
        }else{
            sysResourceMapper.update(sysResource);
        }

        // 更新子节点 parentIds
        SysResource m = new SysResource();
        m.setParentIds("%,"+sysResource.getId()+",%");
        List<SysResource> list = sysResourceMapper.findByParentIdsLike(m);
        for (SysResource e : list){
            e.setParentIds(e.getParentIds().replace(oldParentIds, sysResource.getParentIds()));
            sysResourceMapper.updateParentIds(e);
        }
    }

    @Override
    public int updateSort(SysResource sysResource) {
        return sysResourceMapper.updateSort(sysResource);
    }
}
